<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 角色列表表格内容区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button type="primary" class="searchoradd" @click="addRole"
        >添加角色</el-button
      >
      <el-table :data="roleList" style="width: 100%" stripe border>
        <el-table-column type="expand">
          <!-- 权限列表渲染 -->
          <template v-slot="scope">
            <el-row
              :class="{ bottom: true, top: i1 == 0, rowcenter: true }"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限渲染 -->
              <el-col :span="5">
                <el-tag closable @close="removeTagById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限渲染 -->
              <el-col :span="19">
                <el-row
                  :class="{ top: i2 !== 0, rowcenter: true }"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeTagById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeTagById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 表格序号 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" widht="300px">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-delete"
              size="mini"
              @click="del(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-setting"
              size="mini"
              @click="setRolesRight(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="setRightDialogVisible" width="30%">
      <!-- 树形结构数据区域 -->
      <el-tree
        :data="rightLists"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户对话框 -->
    <!-- 添加关闭用户对话框 close事件,实现关闭对话框之后清空表单的内容 -->
    <el-dialog
      :title="addOreditTitle"
      :visible.sync="addRoleDialog"
      width="30%"
      @close="addRolerClear"
    >
      <!-- 对话框主体内容表单区域 -->
      <el-form
        :model="addRoleForm"
        :rules="addRoleRules"
        ref="addRoleRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="password">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- 对话框底部按钮区域 -->
        <el-button @click="addRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="addOreditRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'Roles',
  data () {
    return {
      //  添加修改用户标题
      addOreditTitle: '',
      //  控制添加角色对话框显示
      addRoleDialog: false,
      // 添加或修改 add or edit
      roleType: '',
      //  添加角色数据
      addRoleForm: {
        roleName: '', //  角色名称不可以为空
        roleDesc: '',// 角色描述 可以为空
      },
      //  角色列表数据
      roleList: [],
      //  分配权限对话框控制
      setRightDialogVisible: false,
      //  所有的权限数据
      rightLists: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //  默认选中的节点
      defKeys: [],
      //  分配角色按钮点击当前行角色id
      rowId: '',
      //  添加角色表单验证
      addRoleRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
      }
    }

  },
  mounted () {
    this.getRolesList()
  },
  methods: {
    //  获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('/roles')
      this.roleList = res.data
    },
    //  根据id删除响应的权限
    removeTagById (row, id) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${id}`)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        } else {
          row.children = res.data
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //  分配权限
    async setRolesRight (row) {
      this.rowId = row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return
      this.rightLists = res.data
      //  调用递归函数
      this.defKeys = []
      this.getLeafKeys(row, this.defKeys)
      this.setRightDialogVisible = true
    },
    //  递归算法获取当前角色所有权限id
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })

    },
    //  分配角色对话框确定按钮点击事件
    async allRights () {
      //  所有权限id存在这个数组
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      let ridStr = keys.join(',')
      //  发送请求
      const { data: res } = await this.$http.post(`roles/${this.rowId}/rights`, { rids: ridStr })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('分配权限成功!')
      //  重新获取角色列表
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    //  添加角色的对话框确定按钮点击事件
    async addOreditRole () {

      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        if (this.roleType === "add") {
          const { data: res } = await this.$http.post('roles', this.addRoleForm)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success('添加成功~')
        } else {
          const { data: res } = await this.$http.put(`roles/${this.rowId}`, this.addRoleForm)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success('修改成功~')
        }
        //  关闭表单
        this.addRoleDialog = false
        // 重新请求用户列表
        this.getRolesList()
      })

    },
    //  添加角色关闭事件
    addRolerClear () {
      //  清空表单
      this.$refs.addRoleRef.resetFields()
    },
    //  编辑角色
    editRole (row) {
      this.addOreditTitle = "编辑角色"
      this.addRoleDialog = true
      this.roleType = "edit"
      this.rowId = row.id
      this.addRoleForm.roleName = row.roleName
      this.addRoleForm.roleDesc = row.roleDesc

    },
    //  添加用户
    addRole () {
      this.addOreditTitle = "添加角色"
      this.addRoleDialog = true
      this.roleType = "add"
    },
    //  角色删除按钮点击事件
    del (id) {
      // 删除对话框
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          //  重新获取列表
          this.getRolesList()
        } else {
          this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 5px;
}
.top {
  border-top: 1px solid #ccc;
}
.bottom {
  border-bottom: 1px solid #ccc;
}
.rowcenter {
  display: flex;
  align-items: center;
}
.searchoradd {
  margin-bottom: 20px;
}
</style>